let pdfDoc = null;
let currentPage = 1;
let canvas = document.getElementById('pdfCanvas');
let ctx = canvas.getContext('2d');
let currentTool = null;
let originalPdfBytes = null;

const statusMsg = document.getElementById('statusMsg');

document.getElementById('pdfFileInput').addEventListener('change', handleFileSelect);
document.getElementById('highlightBtn').addEventListener('click', () => setTool('highlight'));
document.getElementById('textBtn').addEventListener('click', () => setTool('text'));
document.getElementById('imageBtn').addEventListener('click', () => setTool('image'));
document.getElementById('saveBtn').addEventListener('click', savePdf);

function setTool(tool) {
    currentTool = tool;
    statusMsg.textContent = `当前工具：${tool}`;
}

async function handleFileSelect(event) {
    const file = event.target.files[0];
    if (!file) return;
    statusMsg.textContent = '加载中...';

    const reader = new FileReader();
    reader.onload = async function (e) {
        originalPdfBytes = e.target.result;
        const loadingTask = pdfjsLib.getDocument({data: originalPdfBytes});
        pdfDoc = await loadingTask.promise;
        renderPage(currentPage);
        statusMsg.textContent = `已加载：${file.name}`;
    };
    reader.readAsArrayBuffer(file);
}

async function renderPage(num) {
    const page = await pdfDoc.getPage(num);
    const viewport = page.getViewport({scale: 1.5});
    canvas.height = viewport.height;
    canvas.width = viewport.width;

    const renderContext = {canvasContext: ctx, viewport: viewport};
    await page.render(renderContext).promise;

    canvas.onclick = function (e) {
        if (currentTool === 'highlight') drawHighlight(e);
        else if (currentTool === 'text') addText(e);
        else if (currentTool === 'image') addImage(e);
    };
}

function drawHighlight(e) {
    const rectSize = 80;
    ctx.fillStyle = 'rgba(255,255,0,0.5)';
    ctx.fillRect(e.offsetX, e.offsetY, rectSize, 20);
}

function addText(e) {
    const text = prompt('请输入文字：');
    if (text) {
        ctx.font = '16px sans-serif';
        ctx.fillStyle = 'red';
        ctx.fillText(text, e.offsetX, e.offsetY);
    }
}

function addImage(e) {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = 'image/*';
    input.onchange = function (evt) {
        const imgFile = evt.target.files[0];
        const reader = new FileReader();
        reader.onload = function (r) {
            const img = new Image();
            img.onload = function () {
                ctx.drawImage(img, e.offsetX, e.offsetY, 100, 100);
            };
            img.src = r.target.result;
        };
        reader.readAsDataURL(imgFile);
    };
    input.click();
}

async function savePdf() {
    if (!originalPdfBytes) {
        alert("请先加载一个 PDF 文件");
        return;
    }
    statusMsg.textContent = "正在保存...";

    const pdfDocLib = await PDFLib.PDFDocument.load(originalPdfBytes);
    const newBytes = await pdfDocLib.save();

    const blob = new Blob([newBytes], {type: 'application/pdf'});
    const formData = new FormData();
    formData.append('file', blob, 'edited.pdf');

    $.ajax({
        url: '/api/pdf/save',
        type: 'POST',
        data: formData,
        contentType: false,
        processData: false,
        success: function (res) {
            statusMsg.textContent = "另存为成功！";
        },
        error: function () {
            statusMsg.textContent = "保存失败";
        }
    });
}
